package com.dfbz.controller.login;

import com.dfbz.common.Constr;
import com.dfbz.controller.BaseController;
import com.dfbz.model.User;
import com.dfbz.service.UserService;
import com.dfbz.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login/*")
public class LoginController extends BaseController {

    private UserService userService = new UserServiceImpl();
    //登陆
    public void toLogin(HttpServletRequest req, HttpServletResponse resp) {

        String username = req.getParameter("uname");
        String password = req.getParameter("pwd");
        String rememberMe = req.getParameter("rememberMe");
        User user = userService.findByName(username);
        try {
            if (null != user) {
                //比较密码
                if (password.equals(user.getPassword())) {
                    //密码正确，登录成功
                    if (null != rememberMe) {
                        //勾选了 记住我 ，我就将用户信息保存到cookie 里
                        Cookie cookie = new Cookie("uName", username);
                        cookie.setMaxAge(Constr.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    //将用户的真实名字以及部门名称查出来（查询用户基本信息）
                    Map<String, Object> map = userService.findUserBaseInfo(username);
                    req.getSession().setAttribute("userBaseInfo", map);
                    req.getSession().setAttribute("myUserId",map.get("user_id").toString());

                    //更新登陆时间
                    userService.updateLoginTime(user.getId());

                    resp.sendRedirect(req.getContextPath() + "/assets/html/home.jsp");
                    return;
                } else {
                    req.getSession().setAttribute("loginMsg", "密码不正确");
                }
            } else {
                req.getSession().setAttribute("loginMsg", "用户不存在");
            }
            //其余情况，都属于登录失败，重新跳转首页
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //注册
    public void register(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String email = req.getParameter("email");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            boolean b = userService.checkByEmailOrName(email, username);
            if (!b) {
                //不能注册
                req.getSession().setAttribute("registerMsg", "该用户以及邮箱已被注册使用");
                resp.sendRedirect(req.getContextPath() + "/register.jsp");
            } else {
                //可以注册，插入数据之前，检查用户提交的两次密码是否一致
                if (password.equalsIgnoreCase(password2)) {
                    //密码相同，将数据保存到数据库
                    User user = new User();
                    user.setEmail(email);
                    user.setUsername(username);
                    user.setPassword(password);
                    boolean add = userService.addUser(user);
                    if (add) {
                        //添加成功
                        req.getSession().setAttribute("loginMsg", "注册成功");
                        resp.sendRedirect(req.getContextPath() + "/index.jsp");
                    } else {
                        req.getSession().setAttribute("registerMsg", "注册失败");
                        resp.sendRedirect(req.getContextPath() + "/register.jsp");
                    }

                } else {
                    req.getSession().setAttribute("registerMsg", "两次密码不一致");
                    resp.sendRedirect(req.getContextPath() + "/register.jsp");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            User user = userService.findByEmail(email);
            String data = "0";
            if (null != user) {
                data = "1";
            }
            resp.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void checkUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String username = req.getParameter("username");
            User user = userService.findByName(username);
            String data = "0";
            if (null != user) {
                data = "1";
            }
            resp.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            HttpSession session = req.getSession();
            String email = req.getParameter("email");
            User user = userService.findByEmail(email);
            if (null == user) {
                resp.getWriter().write("该邮箱账号不存在");
            } else {
                //发送邮件之前，看会话有没有过期
                Object value = session.getAttribute(email);
                if (null == value) {
                    //下一步，生成验证码,发送邮件
                    String code = userService.sendEmailCode(email);
                    if (code.length() == 4) {
                        //发送成功，保存到session 会话里
                        session.setAttribute(email, code);
                        //存活时间
                        session.setMaxInactiveInterval(Constr.MAX_EMAIL_TIME);
                        resp.getWriter().write("邮件发送成功");
                    } else {
                        resp.getWriter().write("邮件发送失败");
                    }
                } else {
                    resp.getWriter().write("邮件已发送，请查收");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //登出
    public void logout(HttpServletRequest req, HttpServletResponse resp){
        try {
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("uName".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }
            }
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void reset(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String email = req.getParameter("email");
            String code = req.getParameter("code");
            String password = req.getParameter("password");
            User user = userService.findByEmail(email);
            if (null == user) {
                req.getSession().setAttribute("forgetMsg", "该邮箱账户不存在");
                resp.sendRedirect(req.getContextPath() + "/forget.jsp");
            } else {
                //校验，前端发给我的code 和后端发的code 是否一致
                Object value = req.getSession().getAttribute(email);
                if (null == value) {
                    req.getSession().setAttribute("forgetMsg", "验证码已过期");
                    resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                } else {
                    if (value.toString().equals(code)) {
                        //相同，说明用户知道验证码，可以重置密码
                        boolean b = userService.resetPassword(email, password);
                        if (b) {
                            req.getSession().setAttribute("loginMsg", "密码重置成功");
                            resp.sendRedirect(req.getContextPath() + "/index.jsp");
                        } else {
                            req.getSession().setAttribute("forgetMsg", "密码重置失败");
                            resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                        }
                    } else {
                        req.getSession().setAttribute("forgetMsg", "验证码不正确");
                        resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}